package JAVA300.第十一章多线程;

/**信号灯法实现生产者消费者问题
 *
 *
 */



public class thread_18_corp_light {
    public static void main(String[] args) {

        Tv tv = new Tv();
        new Player(tv).start();
        new Watcher(tv).start();



    }

}


//演员
class Player extends Thread{

    Tv tv = new Tv();

    public Player(Tv tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i=0;i<20;i++){
            if (i%2 ==0){
                this.tv.play("奇葩说");

            }else {
                this.tv.play("广告中");
            }


        }

    }
}
//观众

//演员
class Watcher extends Thread{

    Tv tv = new Tv();

    public Watcher(Tv tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i=0;i<20;i++){

                this.tv.watch();


        }

    }
}

//同一份数据-电视

class Tv{
    String voice;
    //信号灯
    //T 演员表演 观众等待
    //F 观众观看 演员等待
    boolean flag = true;

    //表演时
    public synchronized void play(String  voice){
        //演员等待
        if (!flag){//观众观看

            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("表演了"+voice);
        this.voice = voice;
        this.notifyAll();
        this.flag = !this.flag;
    }

    public synchronized void watch(){
        if (flag){

            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("看到了"+voice);//表演啥看啥 用信号灯切换
        this.notifyAll();
        this.flag = !this.flag;
    }
}